/*
 * @(#)MaintSysUserDefinedIndex.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.framework.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.bean.DmsDefaultProfileSetting;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsDocumentDetail;
import com.dcivision.dms.bean.DmsDocumentIndexCache;
import com.dcivision.dms.bean.DmsRetentionSetup;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsDocumentDetailDAObject;
import com.dcivision.dms.dao.DmsDocumentIndexDAObject;
import com.dcivision.dms.dao.DmsRetentionSetupDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.SysUdfFieldValue;
import com.dcivision.framework.bean.SysUserDefinedIndex;
import com.dcivision.framework.bean.SysUserDefinedIndexDetail;
import com.dcivision.framework.dao.SysUdfFieldValueDAObject;
import com.dcivision.framework.dao.SysUserDefinedIndexDAObject;
import com.dcivision.framework.dao.SysUserDefinedIndexDetailDAObject;

/**
  MaintSysUserDefinedIndexAction.java
  This class is for maint system user defined index.
    @author          Phoebe Wong
    @company         DCIVision Limited
    @creation date   01/08/2003
    @version         $Revision: 1.40.2.6 $
 */

public class MaintSysUserDefinedIndexAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.40.2.6 $";

  protected String listName = "";

  public MaintSysUserDefinedIndexAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  
  public String getMajorDAOClassName() {
    return ("com.dcivision.framework.dao.SysUserDefinedIndexDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  
  public String getFunctionCode() {
    return (SystemFunctionConstant.DMS_DOC_PROFILE);
  }

  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    AbstractActionForm maintForm = (AbstractActionForm)form;

    String opMode = (maintForm != null) ? maintForm.getOpMode() : request.getParameter("opMode"); //maintForm.getOpMode();
    String navMode = (maintForm != null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();

    if (GlobalConstant.OP_MODE_REFRESH.equals(opMode)) {
      // Set the function code for current action.
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward != null) {
        return forward;
      }
      refreshFormData(mapping, maintForm, request, response);
      return mapping.findForward(GlobalConstant.NAV_MODE_REFRESH);
    }
    else {
      log.debug("opMode: " + opMode + ", navMode: " + navMode);
      return super.execute(mapping, form, request, response);
    }
  }

  public void refreshFormData(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws
    ApplicationException {
    List resultList = new ArrayList();

    try {
      SessionContainer sessionContainer = this.getSessionContainer(request);
      MaintSysUserDefinedIndexForm UserDefinedIndexForm = (MaintSysUserDefinedIndexForm)form;
      int listSize = 0;
      int intNewField = 0;
      try {
        listSize = TextUtility.parseInteger(request.getParameter("listSize"));
        intNewField = TextUtility.parseInteger(request.getParameter("newField"));
      } catch (Exception e) {
        throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
      }
      if("true".equals(request.getParameter("fieldsOrder"))){
      	intNewField = 0;
      }

      int sum = 0;
      sum = listSize + intNewField;

      //Get Header Form data
      SysUserDefinedIndex userDefinedIndexForm = (SysUserDefinedIndex)UserDefinedIndexForm.getFormData();

      //Set Header Form data
      UserDefinedIndexForm.setFormData(userDefinedIndexForm);
      UserDefinedIndexForm.setDescription(UserDefinedIndexForm.getDescription());
      UserDefinedIndexForm.setUserDefinedType(UserDefinedIndexForm.getUserDefinedType());

      for (int i = 0; i < listSize; i++) {
        SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail = new SysUserDefinedIndexDetail();
        if (! ("".equals(request.getParameter("definedFieldID_" + i))) && ! ("null".equals(request.getParameter("definedFieldID_" + i)))) {
          tmpSysUserDefinedIndexDetail.setID(new Integer(request.getParameter("definedFieldID_" + i)));
        }
        if (userDefinedIndexForm.getID() != null && (!"null".equals(userDefinedIndexForm.getID()))) {
          tmpSysUserDefinedIndexDetail.setUserDefinedID(userDefinedIndexForm.getID());
        }
        if (! ("".equals(request.getParameter("definedField_" + i))) && (!"null".equals(userDefinedIndexForm.getID()))) {
          tmpSysUserDefinedIndexDetail.setFieldName(new String(request.getParameter("definedField_" + i)));
        }
        if (! ("".equals(request.getParameter("definedFieldValue_" + i))) && ! ("null".equals(request.getParameter("definedFieldValue_" + i)))) {
          tmpSysUserDefinedIndexDetail.setFieldValue(request.getParameter("definedFieldValue_" + i));
        }
        if (! ("".equals(request.getParameter("disPlaySeq_" + i))) && ! ("null".equals(request.getParameter("disPlaySeq_" + i)))) {
          tmpSysUserDefinedIndexDetail.setDisplaySeq(new Integer(request.getParameter("disPlaySeq_" + i)));
        }

        String strMandatoryCheckValue = request.getParameter("mandatory_" + i);
        if (strMandatoryCheckValue == null) {
          tmpSysUserDefinedIndexDetail.setMandatory("N");
        }
        else {
          tmpSysUserDefinedIndexDetail.setMandatory("Y");
        }
        
        String strValueSuggestCheckValue = request.getParameter("subvalue_suggest_" + i);
        if (strValueSuggestCheckValue == null) {
        	tmpSysUserDefinedIndexDetail.setValueSuggest("N");
        } else {
        	tmpSysUserDefinedIndexDetail.setValueSuggest("Y");
        }
        
        String strDeleteCheckValue = request.getParameter("delete_" + i);
        if(strDeleteCheckValue == null){
        	tmpSysUserDefinedIndexDetail.setDelete("N");
        }
        else{
        	tmpSysUserDefinedIndexDetail.setDelete("Y");
        }
        
        String strFieldTypeChooseValue = request.getParameter("definedFieldType_" + i);
        tmpSysUserDefinedIndexDetail.setFieldType(strFieldTypeChooseValue);
        
        if ("true".equals(request.getParameter("fieldsOrder"))){
        	resultList.add(tmpSysUserDefinedIndexDetail);
        }
        else{
        	if (strDeleteCheckValue == null) {
              resultList.add(tmpSysUserDefinedIndexDetail);
            } 
        }
        
//        String strDeleteCheckValue = request.getParameter("delete_" + i);
//        if (strDeleteCheckValue == null) {
//          resultList.add(tmpSysUserDefinedIndexDetail);
//        }
      }
      
      
      for (int i=0; i<resultList.size(); i++){
        for(int j=resultList.size()-1;j>i; j--){
          SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail_F = (SysUserDefinedIndexDetail)resultList.get(j);
          SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail_L = (SysUserDefinedIndexDetail)resultList.get(j-1);
          if(!Utility.isEmpty(tmpSysUserDefinedIndexDetail_F.getDisplaySeq())&&!Utility.isEmpty(tmpSysUserDefinedIndexDetail_L.getDisplaySeq())){
            if(tmpSysUserDefinedIndexDetail_F.getDisplaySeq().intValue()<tmpSysUserDefinedIndexDetail_L.getDisplaySeq().intValue()){
          	  SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail_Null = tmpSysUserDefinedIndexDetail_F;
          	  tmpSysUserDefinedIndexDetail_F = tmpSysUserDefinedIndexDetail_L;
          	  tmpSysUserDefinedIndexDetail_L = tmpSysUserDefinedIndexDetail_Null;
          	  resultList.set(j,tmpSysUserDefinedIndexDetail_F);
          	  resultList.set(j-1,tmpSysUserDefinedIndexDetail_L);
            }
          }
        }
      }
      
      UserDefinedIndexForm.setFormListData(resultList);
      UserDefinedIndexForm.setUserDetailList(UserDefinedIndexForm.getUserDetailList());

      request.setAttribute("listSize", new Integer(listSize));
      request.setAttribute("newFieldsSize", new Integer(sum));
      request.setAttribute("newField", new Integer(intNewField));
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
    }
  }

  
  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws
    ApplicationException {
    try {
      SessionContainer sessionContainer = this.getSessionContainer(request);
      Connection conn = this.getConnection(request);
      MaintSysUserDefinedIndexForm UserDefinedIndexForm = (MaintSysUserDefinedIndexForm)form;
      Integer UserDefinedIndexID = new Integer(UserDefinedIndexForm.getID());
      SysUserDefinedIndexDAObject UserDefinedIndexDAO = new SysUserDefinedIndexDAObject(sessionContainer, conn);
      SysUserDefinedIndex userDefinedIndex = (SysUserDefinedIndex)UserDefinedIndexDAO.getObjectByID(UserDefinedIndexID);

      UserDefinedIndexForm.setFormData(userDefinedIndex);
      UserDefinedIndexForm.setDescription(UserDefinedIndexForm.getDescription());
      UserDefinedIndexForm.setUserDefinedType(UserDefinedIndexForm.getUserDefinedType());

      SysUserDefinedIndexDetailDAObject UserDefinedIndexDetailDAO = new SysUserDefinedIndexDetailDAObject(sessionContainer, conn);
      List userDetailList = UserDefinedIndexDetailDAO.getListBySysUserDefinedIndexID(UserDefinedIndexID);
      UserDefinedIndexForm.setFormListData(userDetailList);
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
    } finally {}
  }

  
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws
    ApplicationException {
    List resultList = new ArrayList();
    List fieldValueList = new ArrayList();
    
    try {
      MaintSysUserDefinedIndexForm UserDefinedIndexForm = (MaintSysUserDefinedIndexForm)form;
      SessionContainer sessionContainer = this.getSessionContainer(request);
      Connection conn = this.getConnection(request);
      
      //Create Fields for the defined type of User Defined Index
      int listSize = new Integer(request.getParameter("listSize")).intValue();
      
      int custValidateCount = this.custValidateCount(mapping, form, request, response)-1;
      
      //validate profile name, can not contains invalid character. (lee add 06/12/20 EIP-1160)
      TextUtility.stringValidation(UserDefinedIndexForm.getUserDefinedType());
      
      //checking the Profile field is defined or not
      if(this.custValidate(mapping, form, request, response)){
    	throw new ApplicationException(ErrorConstant.DMS_MESSAGE_IS_ALREADY_DEFINED,null,request.getParameter("definedField_" + custValidateCount));
      }
      
      // Create User Defined Index record.
      SysUserDefinedIndexDAObject userDefinedIndexDAO = new SysUserDefinedIndexDAObject(sessionContainer, conn);
      SysUserDefinedIndexDetailDAObject userDefinedIndexDetailDAO = new SysUserDefinedIndexDetailDAObject(sessionContainer, conn);
      SysUdfFieldValueDAObject userUdfFieldValueDAO = new SysUdfFieldValueDAObject(sessionContainer, conn);
      
      SysUserDefinedIndex userDefinedIndex = (SysUserDefinedIndex)UserDefinedIndexForm.getFormData();
      SysUserDefinedIndexDetail userDefinedIndexDetail = new SysUserDefinedIndexDetail();

      userDefinedIndex = (SysUserDefinedIndex)userDefinedIndexDAO.insertObject(userDefinedIndex);
      
      for (int i = 0; i < listSize; i++) {
        SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail = new SysUserDefinedIndexDetail();

        tmpSysUserDefinedIndexDetail.setUserDefinedID(userDefinedIndex.getID());
        String strFieldTypeChooseValue = request.getParameter("definedFieldType_" + i);
        tmpSysUserDefinedIndexDetail.setFieldType(strFieldTypeChooseValue);
        String fieldName = request.getParameter("definedField_" + i);
        TextUtility.stringValidation(fieldName);
        tmpSysUserDefinedIndexDetail.setFieldName(fieldName);
        if(!"".equals(request.getParameter("disPlaySeq_" + i))&&!"null".equals(request.getParameter("disPlaySeq_" + i))){
          tmpSysUserDefinedIndexDetail.setDisplaySeq(new Integer(request.getParameter("disPlaySeq_" + i)));
        }else{
          tmpSysUserDefinedIndexDetail.setDisplaySeq(new Integer(0));
        }
        
        String strMandatoryCheckValue = request.getParameter("mandatory_" + i);
        if (strMandatoryCheckValue == null) {
          tmpSysUserDefinedIndexDetail.setMandatory("N");
        }
        else {
          tmpSysUserDefinedIndexDetail.setMandatory("Y");
        }

        String strValueSuggestCheckValue = request.getParameter("subvalue_suggest_" + i);
        if (strValueSuggestCheckValue == null) {
        	tmpSysUserDefinedIndexDetail.setValueSuggest("N");
        } else {
        	tmpSysUserDefinedIndexDetail.setValueSuggest("Y");
        }
        
        if (SysUserDefinedIndexDetail.FIELD_TYPE_SELECT_DATABASE.equals(strFieldTypeChooseValue)){
          tmpSysUserDefinedIndexDetail.setSqlStat("SELECT FIELD_VALUE FROM SYS_UDF_FIELD_VALUE WHERE  USER_DEFINED_FIELD_DETAIL_ID  = ?");
        }
        userDefinedIndexDetail = new SysUserDefinedIndexDetail();


        String strDeleteCheckValue = request.getParameter("delete_" + i);
        String strFieldValueOption = request.getParameter("definedFieldValue_" + i);
        if ( (strDeleteCheckValue == null) && ! ("".equals(tmpSysUserDefinedIndexDetail.getFieldName()))) {
          userDefinedIndexDetail = (SysUserDefinedIndexDetail)userDefinedIndexDetailDAO.insertObject(tmpSysUserDefinedIndexDetail);
          resultList.add(userDefinedIndexDetail);
          
          String strFieldType = userDefinedIndexDetail.getFieldType();
          if (SysUserDefinedIndexDetail.FIELD_TYPE_SELECT_DATABASE.equals(strFieldTypeChooseValue)){

            //String strFieldDefault = request.getParameter("defaultSelect_" + i);
            String strFieldDefault = "N";
            StringTokenizer st = new StringTokenizer(strFieldValueOption, ";");
            while (st.hasMoreTokens()) {
              String str = st.nextToken().trim();              
              SysUdfFieldValue fieldValue = new SysUdfFieldValue();
              fieldValue.setUserDefinedFieldDetailID(userDefinedIndexDetail.getID());
              fieldValue.setFieldValue(str);
              fieldValue.setDefaultValue(strFieldDefault);
              fieldValue = (SysUdfFieldValue)userUdfFieldValueDAO.insertObject(fieldValue);
            }
          }
          userDefinedIndexDetail.setFieldValue(strFieldValueOption);
        }
        

      }
      if (resultList.size() <=0) { //Temp solution for null field value
        SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail = new SysUserDefinedIndexDetail();

        tmpSysUserDefinedIndexDetail.setUserDefinedID(userDefinedIndex.getID());
        tmpSysUserDefinedIndexDetail.setFieldName("");
        tmpSysUserDefinedIndexDetail.setMandatory("N");
        
        tmpSysUserDefinedIndexDetail.setValueSuggest("N");
        
        userDefinedIndexDetail = (SysUserDefinedIndexDetail)userDefinedIndexDetailDAO.insertObject(tmpSysUserDefinedIndexDetail);

      }
      
      //joan.xiong add code for bug EIP-1375 by 2007/01/04
      if((!Utility.isEmpty(request.getParameter("periodYear")) && !"null".equals(request.getParameter("periodYear"))) || (!Utility.isEmpty(request.getParameter("periodMonth")) && !"null".equals(request.getParameter("periodMonth"))) || (!Utility.isEmpty(request.getParameter("periodDay")) && !"null".equals(request.getParameter("periodDay")))){
      	DmsRetentionSetup bean = new DmsRetentionSetup();
      	DmsRetentionSetupDAObject dao = new DmsRetentionSetupDAObject(sessionContainer,conn);
      	bean.setObjectID(userDefinedIndex.getID());
      	bean.setPeriodYear(TextUtility.parseIntegerObj(request.getParameter("periodYear")));
      	bean.setPeriodMonth(TextUtility.parseIntegerObj(request.getParameter("periodMonth")));
      	bean.setPeriodDay(TextUtility.parseIntegerObj(request.getParameter("periodDay")));
      	bean.setPriority(request.getParameter("priority"));
      	bean.setActionName(request.getParameter("actionName"));
      	bean.setDescription(request.getParameter("retentionDescription"));
      	bean.setObjectType("P");
      	bean = (DmsRetentionSetup)dao.insertObject(bean);
      }//joan.xiong add code end
      
      if(GlobalConstant.OP_MODE_INSERT.equals(UserDefinedIndexForm.getOpMode()) || GlobalConstant.OP_MODE_COPY.equals(UserDefinedIndexForm.getOpMode())){
      	UserDefinedIndexForm.setFormData(userDefinedIndex);
      	UserDefinedIndexForm.setFormListData(resultList);
      }    
      request.setAttribute("listSize", null);
      request.setAttribute("newFieldsSize", null);
      request.setAttribute("newField", null);
      refreshList(request, GlobalConstant.OP_MODE_INSERT, userDefinedIndex);
    } catch (ApplicationException appEx) {      
      MaintSysUserDefinedIndexForm UserDefinedIndexForm = (MaintSysUserDefinedIndexForm)form;
      getDateList(UserDefinedIndexForm,request);
      //Add By Jim Zhou   2006/10/17    EIP-686
      throw appEx;
      //Add End
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {}
  }

  public void refreshList(HttpServletRequest request, String opMode, com.dcivision.framework.bean.AbstractBaseObject obj) {
    java.util.ArrayList list = (java.util.ArrayList)request.getAttribute(this.listName);
    if (list != null) {
      if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
        list.add(obj);
      }
      else if (GlobalConstant.OP_MODE_UPDATE.equals(opMode)) {
        for (int i = 0; i < list.size(); i++) {
          if (obj.equals(list.get(i))) {
            list.remove(i);
            list.add(i, obj);
          }
        }
      }
      else if (GlobalConstant.OP_MODE_DELETE.equals(opMode)) {
        for (int i = 0; i < list.size(); i++) {
          if (obj.equals(list.get(i))) {
            list.remove(i);
          }
        }
      }
    }
  }

  
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws
    ApplicationException {
    List resultList = new ArrayList();
    SysUserDefinedIndexDetail userDefinedIndexDetail = null;

    try {
      MaintSysUserDefinedIndexForm UserDefinedIndexForm = (MaintSysUserDefinedIndexForm)form;
      SessionContainer sessionContainer = this.getSessionContainer(request);
      Connection conn = this.getConnection(request);
      
      //Create Fields for the defined type of User Defined Index
      request.setAttribute("listSize", new Integer(request.getParameter("listSize")));
      int listSize = new Integer(request.getParameter("listSize")).intValue();
      int custValidateCount = this.custValidateCount(mapping, form, request, response)-1;
      
      //validate profile name, can not contains invalid character. (lee add 06/12/20 EIP-1160)
      TextUtility.stringValidation(UserDefinedIndexForm.getUserDefinedType());
      
      //checking the Profile field is defined or not
      if(this.custValidate(mapping, form, request, response)){
      	this.selectRecord(mapping, form, request, response);
    	throw new ApplicationException(ErrorConstant.DMS_MESSAGE_IS_ALREADY_DEFINED,null,request.getParameter("definedField_" + custValidateCount));
      }
      
      // Create User Defined Index record.
      SysUserDefinedIndexDAObject userDefinedIndexDAO = new SysUserDefinedIndexDAObject(sessionContainer, conn);
      SysUserDefinedIndexDetailDAObject userDefinedIndexDetailDAO = new SysUserDefinedIndexDetailDAObject(sessionContainer, conn);
      SysUdfFieldValueDAObject userUdfFieldValueDAO = new SysUdfFieldValueDAObject(sessionContainer, conn);

      DmsDocumentDetailDAObject documentDetailDAO = new DmsDocumentDetailDAObject(sessionContainer, conn);
      DmsDocumentIndexDAObject documentIndexDAO = new DmsDocumentIndexDAObject(sessionContainer, conn);
      DmsDocumentDAObject documentDAO = new DmsDocumentDAObject(sessionContainer, conn);
      
      SysUserDefinedIndex userDefinedIndexForm = (SysUserDefinedIndex)UserDefinedIndexForm.getFormData();
      SysUserDefinedIndex userDefinedIndex = (SysUserDefinedIndex)userDefinedIndexDAO.updateObject(userDefinedIndexForm);
      
      DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

      
      //log.debug("hello 2...");
      for (int i = 0; i < listSize; i++) {
        SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail = new SysUserDefinedIndexDetail();

        if (! ("".equals(request.getParameter("definedFieldID_" + i))) && ! ("null".equals(request.getParameter("definedFieldID_" + i)))) {
          tmpSysUserDefinedIndexDetail = (SysUserDefinedIndexDetail)userDefinedIndexDetailDAO.getObjectByID(new Integer(request.getParameter("definedFieldID_" + i)));
        }

        tmpSysUserDefinedIndexDetail.setUserDefinedID(userDefinedIndex.getID());
        String fieldName = request.getParameter("definedField_" + i).toString();
        TextUtility.stringValidation(fieldName);
        if(Utility.isEmpty(fieldName) || Utility.isEmpty(fieldName.trim())){
          throw new ApplicationException("error.setup.value_required_error",null,"Field Name");
        }
        tmpSysUserDefinedIndexDetail.setFieldName(fieldName);
        String strFieldTypeChooseValue = request.getParameter("definedFieldType_" + i);
        tmpSysUserDefinedIndexDetail.setFieldType(strFieldTypeChooseValue);
        if(!Utility.isEmpty(request.getParameter("disPlaySeq_" + i)) && !"null".equals(request.getParameter("disPlaySeq_" + i))){
          tmpSysUserDefinedIndexDetail.setDisplaySeq(new Integer(request.getParameter("disPlaySeq_" + i)));
        }

        String strMandatoryCheckValue = request.getParameter("mandatory_" + i);
        if (strMandatoryCheckValue == null) {
          tmpSysUserDefinedIndexDetail.setMandatory("N");
        }
        else {
          tmpSysUserDefinedIndexDetail.setMandatory("Y");
        }
        String strValueSuggestCheckValue = request.getParameter("subvalue_suggest_"+i);
        if (strValueSuggestCheckValue == null) {
        	tmpSysUserDefinedIndexDetail.setValueSuggest("N");
        } else {
        	tmpSysUserDefinedIndexDetail.setValueSuggest("Y");
        }
        
        if (SysUserDefinedIndexDetail.FIELD_TYPE_SELECT_DATABASE.equals(strFieldTypeChooseValue)){
          tmpSysUserDefinedIndexDetail.setSqlStat("SELECT FIELD_VALUE FROM SYS_UDF_FIELD_VALUE WHERE  USER_DEFINED_FIELD_DETAIL_ID  = ?");
        }

        tmpSysUserDefinedIndexDetail.setRecordStatus(userDefinedIndex.getRecordStatus());

        String strDeleteCheckValue = request.getParameter("delete_" + i);
        String strFieldType = "";
        String strFieldValueOption = request.getParameter("definedFieldValue_" + i);

        if (tmpSysUserDefinedIndexDetail.getID() != null) {
          if (strDeleteCheckValue == null) {
            userDefinedIndexDetail = (SysUserDefinedIndexDetail)userDefinedIndexDetailDAO.updateObject(tmpSysUserDefinedIndexDetail);
            resultList.add(userDefinedIndexDetail);
            strFieldType = userDefinedIndexDetail.getFieldType();
            
            if (SysUserDefinedIndexDetail.FIELD_TYPE_SELECT_DATABASE.equals(strFieldTypeChooseValue)){
              Hashtable fieldTable = userUdfFieldValueDAO.getFieldValuesByUdfDetailID(userDefinedIndexDetail.getID());
              userUdfFieldValueDAO.deleteFieldListByUDFDetailID(userDefinedIndexDetail.getID());
              
              //log.debug("definedFieldValue_ "+i + " value = " + strFieldValueOption);              
              String strFieldDefault = "N";
              StringTokenizer st = new StringTokenizer(strFieldValueOption, ";");
              while (st.hasMoreTokens()) {
                String str = st.nextToken().trim();     
                //check the options is new or existing  
                if (fieldTable.containsKey(str) ){
                    //original options
                    fieldTable.remove(str);
                }    
                SysUdfFieldValue fieldValue = new SysUdfFieldValue();
                fieldValue.setUserDefinedFieldDetailID(userDefinedIndexDetail.getID());
                fieldValue.setFieldValue(str);
                fieldValue.setDefaultValue(strFieldDefault);
                fieldValue = (SysUdfFieldValue)userUdfFieldValueDAO.insertObject(fieldValue);
              }
              userDefinedIndexDetail.setFieldValue(strFieldValueOption);
              
              //Check whether any old option are deleted
              if (!Utility.isEmpty(fieldTable)){
                for (Enumeration e = fieldTable.keys() ; e.hasMoreElements() ;) {
                  String voidField = (String)e.nextElement();         
                  //log.debug("going to remove field ="+voidField);
                  documentDetailDAO.cleanProfileValue(null, voidField, userDefinedIndexDetail.getID());
                 // for(int a=1; a<16; a++){
                    //documentIndexDAO.cleanProfileIndexValue("INDEX_"+a, null, voidField, userDefinedIndexDetail.getUserDefinedID());
                 // }                  
                }
              }
            }
            
          }//checked for delete
          else {
            userDefinedIndexDetail = (SysUserDefinedIndexDetail)userDefinedIndexDetailDAO.deleteObject(tmpSysUserDefinedIndexDetail);
            strFieldType = userDefinedIndexDetail.getFieldType();

            //for delete mode, delete the corresponding dmsDocumentDetail table  
            List docWithUdfDetailList = new ArrayList();
            docWithUdfDetailList=documentDAO.getDocumentListByUdfDetailID(tmpSysUserDefinedIndexDetail.getID());   
            documentDetailDAO.deleteByUDFDetailID(tmpSysUserDefinedIndexDetail.getID());
           
           //update the dms Document index table
           if(!Utility.isEmpty(docWithUdfDetailList)){
             for(int j=0;j<docWithUdfDetailList.size();j++){
               DmsDocument tmpDmsDocument =(DmsDocument) docWithUdfDetailList.get(j);
               tmpDmsDocument.setDocumentDetails( documentDetailDAO.getListByDocumentID(tmpDmsDocument.getID()));  
               if(!Utility.isEmpty(tmpDmsDocument.getDocumentDetails())){
                 tmpDmsDocument.setUserDefinedFieldID(((DmsDocumentDetail)tmpDmsDocument.getDocumentDetails().get(0)).getUserDefinedFieldID());
               }
               DmsDocumentIndexCache indexCache = new DmsDocumentIndexCache(tmpDmsDocument.getID(),DmsDocumentIndexCache.ACTION_MODE_UPDATE, DmsDocumentIndexCache.ACTION_TYPE_UPDATE_UDFINDEX, null);
               docOperationManager.indexLUCENE(indexCache, tmpDmsDocument, null, null);
             }
             
           }
            
          }
        }//new field
        else {
          if ( (strDeleteCheckValue == null) && ! ("".equals(tmpSysUserDefinedIndexDetail.getFieldName()))) {
            userDefinedIndexDetail = (SysUserDefinedIndexDetail)userDefinedIndexDetailDAO.insertObject(tmpSysUserDefinedIndexDetail);
            resultList.add(userDefinedIndexDetail);
            strFieldType = userDefinedIndexDetail.getFieldType();
            
            strFieldValueOption = request.getParameter("definedFieldValue_" + i);
            if (SysUserDefinedIndexDetail.FIELD_TYPE_SELECT_DATABASE.equals(strFieldTypeChooseValue)){
              
               //String strFieldDefault = request.getParameter("defaultSelect_" + i);
              String strFieldDefault = "N";
              StringTokenizer st = new StringTokenizer(strFieldValueOption, ";");
              while (st.hasMoreTokens()) {
                String str = st.nextToken().trim();              
                SysUdfFieldValue fieldValue = new SysUdfFieldValue();
                fieldValue.setUserDefinedFieldDetailID(userDefinedIndexDetail.getID());
                fieldValue.setFieldValue(str);
                fieldValue.setDefaultValue(strFieldDefault);
                fieldValue = (SysUdfFieldValue)userUdfFieldValueDAO.insertObject(fieldValue);
              }
            }
            userDefinedIndexDetail.setFieldValue(strFieldValueOption);
         
         
            //get the corresponding dmsDocumentDetail
            List dmsDocumentDetailList = new ArrayList();
            //dmsDocumentDetailList = documentDetailDAO.getByUDFIDGroupByDocumentID(userDefinedIndex.getID());
            
            dmsDocumentDetailList = documentDetailDAO.getDummyDetailByDinstinctDocumentID(userDefinedIndex.getID());
            
            if(!Utility.isEmpty(dmsDocumentDetailList)){
            //if add new field, add an empty field to corresponding DmsDocumentDetail table
              for(int k=0;k<dmsDocumentDetailList.size();k++){
             
                DmsDocumentDetail dmsDocumentDetail = (DmsDocumentDetail)dmsDocumentDetailList.get(k);
                dmsDocumentDetail.setUserDefinedFieldDetailID(userDefinedIndexDetail.getID());
               
                documentDetailDAO.insertFieldNameOnly(dmsDocumentDetail);
                
              }
            }
          }
        }
      }
      
      for (int i=0; i<resultList.size(); i++){
      	//SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail = (SysUserDefinedIndexDetail)resultList.get(i);
      	//Integer displaySeqID =  tmpSysUserDefinedIndexDetail.getDisplaySeq();
      	
        for(int j=resultList.size()-1;j>i; j--){
          SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail_F = (SysUserDefinedIndexDetail)resultList.get(j);
          SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail_L = (SysUserDefinedIndexDetail)resultList.get(j-1);
          if(!Utility.isEmpty(tmpSysUserDefinedIndexDetail_F.getDisplaySeq())&&!Utility.isEmpty(tmpSysUserDefinedIndexDetail_L.getDisplaySeq())){
            if(tmpSysUserDefinedIndexDetail_F.getDisplaySeq().intValue()<tmpSysUserDefinedIndexDetail_L.getDisplaySeq().intValue()){
          	  SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail_Null = tmpSysUserDefinedIndexDetail_F;
          	  tmpSysUserDefinedIndexDetail_F = tmpSysUserDefinedIndexDetail_L;
          	  tmpSysUserDefinedIndexDetail_L = tmpSysUserDefinedIndexDetail_Null;
          	  resultList.set(j,tmpSysUserDefinedIndexDetail_F);
          	  resultList.set(j-1,tmpSysUserDefinedIndexDetail_L);
            }
          }
        }
      }

      UserDefinedIndexForm.setFormData(userDefinedIndex);
      UserDefinedIndexForm.setFormListData(resultList);
      request.setAttribute("listSize", null);
      request.setAttribute("newFieldsSize", null);
      request.setAttribute("newField", null);
      refreshList(request, GlobalConstant.OP_MODE_INSERT, userDefinedIndex);
    } catch (ApplicationException appEx) {
      this.selectRecord(mapping, form, request, response);
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {}
  }

  
  public void clearUniqueFields(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws
    ApplicationException {
    MaintSysUserDefinedIndexForm sysUserDefinedIndexForm = (MaintSysUserDefinedIndexForm)form;
    sysUserDefinedIndexForm.setUserDefinedType(null);
  }
  
  
  public void deleteRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws
    ApplicationException {
    
    try {
      MaintSysUserDefinedIndexForm UserDefinedIndexForm = (MaintSysUserDefinedIndexForm)form;
      SessionContainer sessionContainer = this.getSessionContainer(request);
      Connection conn = this.getConnection(request);
      // Delete User Defined Index record.
      SysUserDefinedIndexDetailDAObject userDefinedIndexDetailDAO = new SysUserDefinedIndexDetailDAObject(sessionContainer, conn);
     
      SysUdfFieldValueDAObject userUdfFieldValueDAO = new SysUdfFieldValueDAObject(sessionContainer, conn);    
      Integer UserDefinedIndexID = new Integer(UserDefinedIndexForm.getID());
      List udfDetailList = userDefinedIndexDetailDAO.getListBySysUserDefinedIndexID(UserDefinedIndexID);
      if (!Utility.isEmpty(udfDetailList)){
        for (int i=0; i<udfDetailList.size(); i++) {
          SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail = (SysUserDefinedIndexDetail)udfDetailList.get(i);
          if (SysUserDefinedIndexDetail.FIELD_TYPE_SELECT_DATABASE.equals(tmpSysUserDefinedIndexDetail.getFieldType())){
            userUdfFieldValueDAO.deleteFieldListByUDFDetailID(tmpSysUserDefinedIndexDetail.getID());
          }
          userDefinedIndexDetailDAO.deleteObject(tmpSysUserDefinedIndexDetail);
        }
      }
      super.deleteRecord(mapping, form, request, response);
      
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {}
  }
  
  //checking the Profile field is defined or not 
  public boolean custValidate(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException{
  	boolean flag = false;
  	
  	SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer,conn);
    
    List defaultProfileField = docRetrievalManager.checkNSetDefaultProfileList(request);    
    
    int listSize = new Integer(request.getParameter("listSize")).intValue();
    
    for (int i = 0; i < listSize; i++) { 
      String definedField= new String(request.getParameter("definedField_" + i));
      String definedFieldLowerCase =(new String(request.getParameter("definedField_" + i))).toLowerCase();
      for(int j=0;j<defaultProfileField.size();j++){
        DmsDefaultProfileSetting dmsDefaultProfileSetting = (DmsDefaultProfileSetting)defaultProfileField.get(j);            
        if("reference number".equals(definedFieldLowerCase)||"description".equals(definedFieldLowerCase)||dmsDefaultProfileSetting.getFieldName().equals(definedField)){
          flag = true;
          break;
        }
      }
    }
  	return flag;  
  }
  
  public int custValidateCount(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException{
  	int count = 0;
  	boolean flag =false;
  	
  	SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer,conn);
    
    List defaultProfileField = docRetrievalManager.checkNSetDefaultProfileList(request);    
    
    int listSize = new Integer(request.getParameter("listSize")).intValue();
    
    for (int i = 0; i < listSize; i++) {    	
      count = count+1;
      String definedField= new String(request.getParameter("definedField_" + i));
      String definedFieldLowerCase =(new String(request.getParameter("definedField_" + i))).toLowerCase();
      for(int j=0;j<defaultProfileField.size();j++){
        DmsDefaultProfileSetting dmsDefaultProfileSetting = (DmsDefaultProfileSetting)defaultProfileField.get(j);      
        if("reference number".equals(definedFieldLowerCase)||"description".equals(definedFieldLowerCase)||dmsDefaultProfileSetting.getFieldName().equals(definedField)){
          flag =true;
          break;
        }
      }
      if(flag){
      	break;
      }
    }
    return count;
  }
  
  public void getDateList(AbstractActionForm form, HttpServletRequest request)throws ApplicationException{
    int listSize = new Integer(request.getParameter("listSize")).intValue();
    List resultList = new ArrayList();
    MaintSysUserDefinedIndexForm UserDefinedIndexForm = (MaintSysUserDefinedIndexForm)form;
    for (int i = 0; i < listSize; i++) {
      SysUserDefinedIndexDetail userDefinedIndexDetail = new SysUserDefinedIndexDetail();
      if (! ("".equals(request.getParameter("definedFieldID_" + i))) && ! ("null".equals(request.getParameter("definedFieldID_" + i)))) {
        userDefinedIndexDetail.setID(new Integer(request.getParameter("definedFieldID_" + i)));
      }
      if (UserDefinedIndexForm.getID() != null && (!"null".equals(UserDefinedIndexForm.getID()))) {
        userDefinedIndexDetail.setUserDefinedID(TextUtility.parseIntegerObj(UserDefinedIndexForm.getID()));
      }
      if (! ("".equals(request.getParameter("definedField_" + i))) && (!"null".equals(UserDefinedIndexForm.getID()))) {
        userDefinedIndexDetail.setFieldName(new String(request.getParameter("definedField_" + i)));
      }
      if (! ("".equals(request.getParameter("definedFieldValue_" + i))) && ! ("null".equals(request.getParameter("definedFieldValue_" + i)))) {
        userDefinedIndexDetail.setFieldValue(request.getParameter("definedFieldValue_" + i));
      }
      if (! ("".equals(request.getParameter("disPlaySeq_" + i))) && ! ("null".equals(request.getParameter("disPlaySeq_" + i)))) {
        userDefinedIndexDetail.setDisplaySeq(new Integer(request.getParameter("disPlaySeq_" + i)));
      }

      String strMandatoryCheckValue = request.getParameter("mandatory_" + i);
      if (strMandatoryCheckValue == null) {
        userDefinedIndexDetail.setMandatory("N");
      }
      else {
        userDefinedIndexDetail.setMandatory("Y");
      }
      
      String strDeleteCheckValue = request.getParameter("delete_" + i);
      if(strDeleteCheckValue == null){
        userDefinedIndexDetail.setDelete("N");
      }
      else{
        userDefinedIndexDetail.setDelete("Y");
      }
      
      String strFieldTypeChooseValue = request.getParameter("definedFieldType_" + i);
      userDefinedIndexDetail.setFieldType(strFieldTypeChooseValue);
      
      if ("true".equals(request.getParameter("fieldsOrder"))){
        resultList.add(userDefinedIndexDetail);
      }
      else{
        if (strDeleteCheckValue == null) {
          resultList.add(userDefinedIndexDetail);
        } 
      }
    }

    UserDefinedIndexForm.setFormListData(resultList);
    UserDefinedIndexForm.setUserDetailList(UserDefinedIndexForm.getUserDetailList());

    request.setAttribute("listSize", new Integer(listSize));
  }
}